Purpose

This document is based on Gemma’s code.

This is a template for fitting sdmTMB to GOA bottom trawl data. For each species, it fits sdmTMB to life stages (juveniles or adults) to predict CPUE in number of individuals per km\(^{2}\). This predicted CPUE is then scaled up to box area in Atlantis, to get numbers of individuals per box and proportion of the total by box, which is what we need to initialise Atlantis. This same code will be run for biomass pool species too, except for those we will not split inot juveniles and adults, and we will use CPUE in biomass.

This workflow does not include British Columbia: biomasses and/or numbers of individuals for the Atlantis boxes in the Canadian part of the model will be estimated separately by using this code, with some adjustments, on DFO groundfish bottom trawl data.

This workflow is based on the following assumptions:

  1. We use lat, lon and depth as predictors. We do not use environmental covariates as predictors because we are not attempting to explain why fish species are distributed the way they are, but rather we are trying to have sensible generic distributions over the model domain throughout the study period (1984-2019).
  2. We predict over a regular grid. The size of this grid is 10 km at the moment for computational efficiency, but this is arbitrary and we may need to test different grid sizes and see how the results change. After some testing with predicting over a grid of 1 point per Atlantis box, I chose to use a regular grid because: (1) an average value of lat and lon, such as a centroid, is difficult to calculate for some of the boxes with crescent shapes; and (2) some boxes are placed over areas where depth changes greatly (the GOA bathymetry is complex), and the inside points may fall inside or near a deeper/shallower area withih a certain box. While the Atlantis box itself has a constant depth, the nearest node of the SPDE mesh may have been near such deeper/shallower area, thus skewing the estimate of the biomass index for that particular box.
  3. We are not so interested in accurate predictions for any one year, but rather in representative means of where the fish has been over the last few decades. This code runs a temporal model and takes averages of the estimates at the end.
select <- dplyr::select

Read data

load("data/cpue.atf.A.Rdata")
race_data <- as_tibble(dat_stage)

This is CPUE data for ATF as I received from Gemma (who in turn got it from Kirstin), except the 10-cm size bins have been aggregated into juveniles (J) and adults (A) based on length at 50% maturity. This aggregation occurred at haul level. There are a lot of fields, so let’s select what we need and drop the rest.

Note: for lat and lon, for now I am using the start values for each tow, but it would be easy to get the coordinates for the midpoint of the tow.

fields <- c("YEAR",
            "HAULJOIN",
            "LAT", 
            "LON", 
            "DEPTHR", 
            "SST", 
            "TEMPR", 
            "SPECIES_CODE", 
            "CN",
            "BIOM_KGKM2", 
            "NUM_KM2",
            "STAGE")
  
race_data <- race_data %>% select(all_of(fields)) %>% set_names(c(
  "year",
  "hauljoin",
  "lat",
  "lon",
  "depth",
  "stemp",
  "btemp",
  "species_code",
  "name",
  "biom_kgkm2",
  "num_km2",
  "stage"))

Take a quick look at the data spatially.

# coast for plotting
load("data/goa_coast.Rdata")
coast_sf <- st_as_sf(coast) # turn coast to sf

ggplot()+
  geom_point(data = race_data, aes(lon, lat, colour = log1p(num_km2)), size = 1.5)+
  scale_colour_viridis_c()+
  geom_polygon(data = coast, aes(x = long, y = lat, group = group), colour = "black", fill = "grey80")+
  theme_minimal()+
  facet_wrap(~year, ncol = 2)+
  labs(title = paste(race_data$name,"CPUE from GOA bottom trawl survey - stage:", race_data$stage, sep = " "))
## Regions defined for each Polygons

Take a quick look at time series of total numbers CPUE from raw data

num_year <- race_data %>% group_by(year) %>% summarise(num = sum(log1p(num_km2)))

ggplot(num_year, aes(year, log(num)))+
  geom_point()+
  geom_path()+
  theme_minimal()+
  labs(title = paste(race_data$name,"total GOA CPUE from bottom \n trawl survey - stage:", race_data$stage, sep = " "))

The above is across the entire GOA.

Add zeroes for hauls with no catch

Kirstin’s CPUE data includes empty hauls (i.e. zero catches). However, in the step where aggregate the size bin data into life-stage data (not included in this code), we loose those empty hauls (as BIN will be NA for a haul whith zero catch in Kirstin’s data set, which causes zero cathces to be dropped when I join by HAULJOIN). So, we need to add them back to the RACE data here. To do this, I take haul information from the “Haul Descriptions” data set on AKFIN. I then subtract the RACE hauls with catch in race_data from the “Haul Descriptions” list to see which hauls were empty for this particular species / life stage. Then pad these empty hauls with zero CPUEs, and attach them to race_data.

load("data/hauls.Rdata") # as accessible on AKFIN Answers with no further modifications

data_hauls <- levels(factor(race_data$hauljoin))
zero_hauls <- setdiff(levels(factor(hauls$Haul.Join.ID)), data_hauls) # assuming that if there are no records from a haul, the catch in that haul was 0 for this species

# make a data frame to bind by row
zero_catches <- hauls %>% filter(Haul.Join.ID %in% zero_hauls) %>% 
  select(Year, Haul.Join.ID, Ending.Latitude..dd., Ending.Longitude..dd., Bottom.Depth..m., Surface.Temperature..C., Gear.Temperature..C.) %>% 
  mutate(species_code = rep(NA, length(Year)),
         name = rep(NA, length(Year)),
         biom_kgkm2 = rep(0, length(Year)),
         num_km2 = rep(0, length(Year)),
         stage = rep(NA, length(Year))) %>%
  set_names(names(race_data))

# attach by row to race_data
race_data <- rbind(race_data, zero_catches)
# ditch hauls with empty lat or lon
race_data <- race_data %>% filter(!is.na(lat) | !is.na(lon))
# and with NA depths
race_data <- race_data %>% filter(!is.na(depth))

sdmTMB

Create spatial mesh

This is the mesh that the sdmTMB algorithm uses to estimate spatial autocorrelation. Using 450 knots for the atual models, since this is a large area. More than that becomes computationally demanding. Using 100 here for demonstration purposes.

Note: SPDE = Stochastic Partial Differential Equations approach. Some material can be found here, but basically it is a way of calculating the position of the mesh knots.

race_spde <- make_mesh(race_data, c("lon", "lat"), n_knots = 750) # usually 450
plot(race_spde)

Check out the distribution of the number of individuals response variable.

hist(race_data$num_km2, breaks = 30)

hist(log1p(race_data$num_km2), breaks = 30)

Proportion of zeroes in percentage.

length(which(race_data$num_km2 == 0))/nrow(race_data)*100
## [1] 28.02988

Space, time, and depth model.

Try running a model with smooth term for depth. Using 5 knots for the smooth - but this is arbitrary and a range of values could be tested. As a note, I am not scaling depth here. The reason is that depth has a different range in the data and the prediction grid, and thus scaled values have different meaning between the two.

Model type: the distribution of the response variable plotted above should give a sense of what model is most appropriate. CPUE data for many of these species resemble a Tweedie distribution when log-transformed, so we use a Tweedie model with a log link. Some groups may warrant a different model, and this will be evaluated case-by-case depending on convergence issues, distribution of model residuals, and model skill metrics (see below).

Check information on model convergence. From the nlminb help page we know that an integer 0 indicates succesful convergence. Additional information on convergence can be checked with m_depth$model$message. According to the original PORT optimization documentation, “Desirable return codes are 3, 4, 5, and sometimes 6”.

if(m_depth$model$convergence == 0){print("The model converged.")} else {print("Check convergence issue.")}
## [1] "The model converged."
m_depth$model$message
## [1] "relative convergence (4)"

Check out model residuals.

race_data$resids <- residuals(m_depth) # randomized quantile residuals
hist(race_data$resids)

And QQ plot.

qqnorm(race_data$resids)
abline(a = 0, b = 1)

Plot the response curve from the depth smooth term.

plot(m_depth$mgcv_mod, rug = TRUE)

Finally, plot the residuals in space. If residuals are constantly larger/smaller in some of the areas, it may be sign that the model is biased and it over/underpredicts consistently for some areas. Residuals should be randomly distributed in space. We need to read in the Atlantis BGM file to do that, as we need the right projection.

Read in BGM and coast.

atlantis_bgm <- read_bgm("data/GOA_WGS84_V4_final.bgm")
race_sf <- race_data %>% st_as_sf(coords = c(x = "lon", y = "lat"), crs = "WGS84") %>% st_transform(crs = atlantis_bgm$extra$projection) # turn to spatial object

ggplot()+
  geom_sf(data = race_sf, aes(color = resids, alpha = .8))+
  scale_color_viridis()+
  geom_sf(data = coast_sf)+
  theme_minimal()+
  labs(title = paste(race_data$name,"model residuals in space - stage:", race_data$stage, sep = " "))+
  facet_wrap(~year, ncol = 2)

Predictions from SDM

Take a grid (which must contain information on the predictors we used to build the model) and predict the biomass index over such grid based on the predictors.

  1. The grid is currently a regular grid with 10-km cell size, but 10 km might not be enough to get prediction points in all boxes - especially for a couple very small and narrow boxes at the western end of the model domain. Revisit this if necessary, but a finer mesh could be difficult to justify compared to the density of the survey data.
  2. The grid covers the entire Atlantis model domain, including the non-dynamic boundary boxes (deeper than 1000 m). The grid at the moment also includes Canada boxes, although predictions for these boxes will not be considered here.

Read in the Atlantis prediction grid (10 km) modified in Atlantis_grid_covars.R (code not included here).

atlantis_boxes <- atlantis_bgm %>% box_sf()

Important: depth in the RACE data is a positive number. Depth in the prediction grid we obtained from the ETOPO rasters is a negative number. When we use depth as predictor for in our regular grid, make sure depth is a positive number for consistency with the model variable, or else everything will be upside-down. This was done in the script that produces the prediction grid, so depth is positive.

load("data/atlantis_grid_depth.Rdata")

#atlantis_grid_depth <- atlantis_grid_depth %>% mutate(depth = -depth) # making sure that depth has the same sign/orientation in the data and prediction grid

# add coordinate columns
atlantis_coords <- atlantis_grid_depth %>% st_as_sf(coords = c("x", "y"), crs = atlantis_bgm$extra$projection) %>%
  st_transform(crs = "+proj=longlat +datum=WGS84") %>% dplyr::select(geometry)

atlantis_grid <- cbind(atlantis_grid_depth, do.call(rbind, st_geometry(atlantis_coords)) %>%
    as_tibble() %>% setNames(c("lon","lat")))
## Warning: The `x` argument of `as_tibble.matrix()` must have unique column names if `.name_repair` is omitted as of tibble 2.0.0.
## Using compatibility `.name_repair`.
paste("Positive depths are:", length(which(atlantis_grid$depth>0)), "out of:", nrow(atlantis_grid_depth), sep = " ") # Write out a check that depths are positive (few negatives are OK - they are on land - I'll fix it but it should not matter as island boxes will be boundary boxes in Atlantis so predictions will not matter for those)
## [1] "Positive depths are: 6237 out of: 6259"
# add year column
all_years <- levels(factor(race_data$year))

atlantis_grid <- atlantis_grid[rep(1:nrow(atlantis_grid), length(all_years)),]
atlantis_grid$year <- as.integer(rep(all_years, each = nrow(atlantis_grid_depth)))

Visualise the prediction grid.

coast_tmp <- map("worldHires", regions = c("Canada", "USA"), plot = FALSE, fill = TRUE)
coast_tmp <- coast_tmp %>% st_as_sf() 

atlantis_grid %>% filter(year == 1984) %>%
  st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
  ggplot()+
  geom_sf(size = 0.1)+
  geom_sf(data = coast_tmp)+
  coord_sf(xlim = c(-172,-128), ylim = c(50, 61))+
  theme_minimal()+
  labs(title = "Prediction grid")

Make SDM predictions onto new data from depth model. Back-transforming here

predictions_race <- predict(m_depth, newdata = atlantis_grid, return_tmb_object = TRUE)
atlantis_grid$estimates <- exp(predictions_race$data$est) #Back-transforming here

atlantis_grid_sf <- atlantis_grid %>% st_as_sf(coords = c("x", "y"), crs = atlantis_bgm$extra$projection) # better for plots

Not plotting most of Canada because the predictions look terrible (due to not having biomass data from there in this model).

ggplot()+
  geom_sf(data = subset(atlantis_boxes, box_id < 92), aes(fill = NULL))+
  geom_sf(data = subset(atlantis_grid_sf, box_id < 92), aes(color=log1p(estimates)))+ # taking the log for visualisation
  geom_sf(data = coast_sf, colour = "black", fill = "grey80")+
  scale_color_viridis(name = expression(paste("Log(CPUE) num ", km^-2)))+
  theme_minimal()+
  labs(title = paste(race_data$name,"predicted CPUE - stage:", race_data$stage, sep = " "))+
  facet_wrap(~year, ncol = 2)

Attribute the predictions to their respective Atlantis box, so that we can take box averages.

atlantis_grid_means <- atlantis_grid %>% group_by(year, box_id) %>%
  summarise(mean_estimates = mean(estimates, na.rm = TRUE)) %>% ungroup() 
## `summarise()` has grouped output by 'year'. You can override using the `.groups` argument.
# join this with the box_sf file

predictions_by_box <- atlantis_boxes %>% inner_join(atlantis_grid_means, by = "box_id")

See estimates per box for all years. Silence boundary boxes as they throw the scale out of whack (and they do not need predictions).

predictions_by_box <- predictions_by_box %>% rowwise() %>% mutate(mean_estimates = ifelse(isTRUE(boundary), NA, mean_estimates))

ggplot()+
  geom_sf(data = predictions_by_box[predictions_by_box$box_id<92,], aes(fill = log1p(mean_estimates)))+ # taking the log for visualisation
  scale_fill_viridis(name = expression(paste("Log(CPUE) num ", km^-2)))+
  theme_minimal()+
  geom_sf(data = coast_sf, colour = "black", fill = "grey80")+
  facet_wrap(~year, ncol = 2)+
  labs(title = paste(race_data$name, "mean predicted CPUE by Atlantis box - stage:", race_data$stage, sep = " "))

Plot the raw data again for comparison.

ggplot()+
  geom_point(data = race_data, aes(lon, lat, colour = log1p(num_km2)), size = 1.5, alpha = .5)+ # taking the log for visualisation
  scale_colour_viridis_c(name = expression(paste("Log(CPUE) num ", km^-2)))+
  geom_polygon(data = coast, aes(x = long, y = lat, group = group), colour = "black", fill = "grey80")+
  theme_minimal()+
  facet_wrap(~year, ncol = 2)+
  labs(title = paste(race_data$name,"CPUE from GOA bottom trawl survey - stage:", race_data$stage, sep = " "))
## Regions defined for each Polygons

Have a look at CPUE by depth. This is rough and quick, keep in mind that most tows happen below 300 m, so the sample is not equal between depths.

ggplot(data = race_data, aes(x = depth, y = log1p(num_km2), color = log1p(biom_kgkm2)))+
  scale_color_viridis()+
  geom_point()+
  theme_minimal()+
  labs(title = "CPUE by depth")

Plot data and predictions distributions.

ggplot(data = race_data, aes(log1p(num_km2)))+
  geom_histogram(colour = "black", fill = 'grey80')+
  theme_minimal()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

ggplot(data = predictions_by_box, aes(log1p(mean_estimates)))+
  geom_histogram(colour = "black", fill = 'grey80')+
  theme_minimal()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 224 rows containing non-finite values (stat_bin).

Mean predictions for the study period

Now calculate means of the predictions for the entire study period. Doing it by taking 1984-2019 averages for each Atlantis box.

means_all_years <- predictions_by_box %>% group_by(box_id, area, boundary) %>% summarise(all_years_numkm2 = mean(mean_estimates)) %>% ungroup()
## `summarise()` has grouped output by 'box_id', 'area'. You can override using the `.groups` argument.
ggplot()+
  geom_sf(data = means_all_years[means_all_years$box_id < 92,], aes(fill = log1p(all_years_numkm2)))+ # log for visualisation
  scale_fill_viridis(name = expression(paste("Log(CPUE) num ", km^-2)))+
  geom_sf(data = coast_sf, colour = "black", fill = "grey80")+
  theme_minimal()+
  labs(title = paste(race_data$name, "mean predicted CPUE by Atlantis box (1984-2019) - stage:", race_data$stage, sep = " "))

Model skill

Trying to evaluate model skill by having a look at how well model predictions align with observations.

Since this is a spatially-explicit approach, we need observations and predictions at the same location. We use the locations of all RACE hauls as a prediction grid.

#make a prediction grid from the race data itself
race_grid_tmp <- race_data %>% dplyr::select(lon, lat, depth)

# add year
race_grid <- race_grid_tmp[rep(1:nrow(race_grid_tmp), length(all_years)),]
race_grid$year <- as.integer(rep(all_years, each = nrow(race_grid_tmp)))

# predict on this grid
predictions_at_locations <- predict(m_depth, newdata = race_grid, return_tmb_object = TRUE)
race_grid$predictions <- exp(predictions_at_locations$data$est) # back-transforming here

Now join by year and coordinates to have predictions at the sampling points.

race_corr <- race_data %>% left_join(race_grid, by = c("year", "lat", "lon"))

Observed versus predicted

paste0("Pearson's coef observations vs predictions: ", cor(race_corr$num_km2, race_corr$predictions, use = "everything", method = "pearson"))
## [1] "Pearson's coef observations vs predictions: 0.780583814916285"

Plot.

ggplot(race_corr, aes(x = log1p(predictions), y = log1p(num_km2)))+ # log for visualisation
  geom_point(aes(color = depth.y))+
  scale_color_viridis()+
  geom_abline(intercept = 0, slope = 1)+
  theme_minimal()+
  facet_wrap(~year, scales = "free")+
  labs(title = paste(race_data$name, "observed vs predicted CPUE. Stage: ", race_data$stage, sep = " "))

These models often underpredict zeroes.

Root Mean Square Error (RMSE)

Calculate RMSE between predicted and observed values.

paste("RMSE:", sqrt(mean(race_corr$predictions - race_corr$num_km2)^2), " num km-2", sep = " ") ### traditional rmse metric, in units num km2
## [1] "RMSE: 265.331543419297  num km-2"

Normalised RMSE.

rmse_cv <- sqrt(mean((race_corr$predictions - race_corr$num_km2)^2))/(max(race_corr$num_km2)-min(race_corr$num_km2))*100 #### normalised rmse, expressed as a % of the range of observed biomass values, sort of approximates a coefficient of variation 
paste("Normalised RMSE:", paste0(rmse_cv, "%"), sep = " ")
## [1] "Normalised RMSE: 1.36674171276853%"

Total numbers and numbers per box

The current estimated CPUE is in num km\(^{-2}\). So, just we just turn that into fish per box (biomass pools groups will follow the same workflow except the model will predict biomass CPUE). Remember that the area is in m\(^2\) for the boxes, so need to divide by 1,000,000.

Do this separate for Alaska and Canada, since we are using different data. Total biomass to calculate only for the respective regions, as well as box biomass. Proportional biomass (S1-S4), instead, makes sense only for the entire model domain, so that will be in another script.

means_all_years <- means_all_years %>% mutate(numbers = all_years_numkm2*area*1e-06)

means_alaska <- means_all_years %>% filter(box_id<92)
means_alaska %>% select(box_id, all_years_numkm2, numbers) %>% st_set_geometry(NULL) %>% kable(align = 'lccc', format = "markdown", 
      col.names = c("Box", "CPUE (num km-2)", "Number of individuals"))
Box CPUE (num km-2) Number of individuals
0 NA NA
2 NA NA
3 75.82988 74316.29
4 317.10105 660363.61
5 256.59349 680913.98
6 59.94685 122868.58
7 370.35734 1232495.81
8 NA NA
9 581.69213 1465263.32
10 263.16073 97563.00
11 NA NA
12 262.46771 1314457.10
13 463.03509 4556830.00
14 34.72367 61002.64
15 244.45724 342510.53
16 122.17744 429665.86
17 947.80939 3850723.38
18 1582.16807 12806404.88
19 61.70418 83296.52
20 801.31447 955230.43
22 189.39263 469763.36
23 698.88918 1239669.98
24 2000.27310 16806184.66
25 565.82843 5200057.66
26 296.03634 693040.08
27 1261.09653 7014698.96
28 580.00603 1746314.18
29 2172.59337 16113251.86
30 NA NA
31 57.13096 334640.61
32 2615.57570 2929432.19
33 2015.93530 7848339.81
34 4903.08594 21883537.84
35 71.92516 495720.36
36 4201.13911 3338420.94
37 3503.85258 25965824.59
38 146.00453 541311.59
39 4281.89409 24442699.65
41 1827.96490 1190711.10
42 3524.58171 14795526.70
43 1094.42272 2121135.61
44 264.83266 463243.78
45 878.44132 6231856.51
46 37.01436 199200.24
47 897.90950 5093188.54
48 3084.61497 52434300.67
49 759.55424 2664026.61
50 1030.17951 4517514.81
51 5078.02694 33691394.84
52 1968.16317 7498760.29
53 NA NA
54 1827.48200 1355218.54
55 1460.06085 16311226.31
56 752.82215 3823356.80
57 554.71497 64198.57
58 NA NA
59 27.55002 60615.57
60 1189.94515 1102259.36
61 991.43714 1763877.05
62 NA NA
64 690.59160 3752920.31
65 319.21264 337578.03
66 1104.70974 1176124.79
67 1267.55381 7602080.26
68 209.57960 171561.81
69 NA NA
70 228.42111 199205.19
71 810.12211 3917248.32
72 34.05004 63314.36
73 379.13389 589886.63
74 748.79552 4039535.36
75 564.07658 2404717.42
76 807.47499 2489624.23
77 29.37908 20084.94
78 820.75176 2785627.59
79 1067.29081 12097947.32
80 141.44616 132347.89
81 NA NA
82 1120.59769 2022228.58
83 1272.26472 2965979.49
84 328.13777 571603.78
85 34.42393 122638.89
87 622.81260 734975.66
88 388.98942 2785015.78
89 NA NA
90 931.71929 4101623.19
91 458.70950 714235.09